package cn.engage.login;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginFilter extends ZuulFilter {
  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {
    RequestContext currentContext = RequestContext.getCurrentContext();
    // 从请求头中获取到url
    String requestURI = currentContext.getRequest().getRequestURI();
    // 放行公共资源
    if (requestURI.endsWith("login") || requestURI.endsWith("register")){
      return false;
    }
    // 如果用户访问的不是公共资源，那么需要执行run方法检查token
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    // 获取上下文路径
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();
    // 从头里面获取token
    String token = request.getHeader("token");
    if (StringUtils.isBlank(token)){
      Map<String,Object> map = new HashMap<String,Object>();
      map.put("success",false);
      map.put("message","未登录！");
      map.put("resultObj","nologin");
      String string = JSONObject.toJSONString(map);
      HttpServletResponse response = currentContext.getResponse();
      // 设置响应字符集
      response.setContentType("application/json;charset=utf-8");
      try {
        PrintWriter writer = response.getWriter();
        writer.write(string);
        writer.close();
        // 切断后续filter执行
        RequestContext.getCurrentContext().setSendZuulResponse(false);
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
    return null;
  }
}
